package com.pablito.webapp.interceptor;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class UserRoleRedirectInterceptor implements Interceptor {

	private static final long serialVersionUID = 8101885046038966391L;
	private String roleToCheck;
	private String redirectUrl;
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String result = null;
		validateParams();
		HttpServletRequest request = ServletActionContext.getRequest();
		if (request.isUserInRole(roleToCheck) && !invocation.getProxy().getActionName().equalsIgnoreCase(redirectUrl)) {
			result = redirectUrl;
		} else {
			result = invocation.invoke();
		}
		
		return result;
	}

	private void validateParams() throws ServletException, IOException {
		if (StringUtils.isEmpty(redirectUrl) || StringUtils.isEmpty(roleToCheck)) {
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpServletResponse response = ServletActionContext.getResponse();
			handleNotAuthorized(request, response);
		}
	}
	
	protected void handleNotAuthorized(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.sendError(HttpServletResponse.SC_FORBIDDEN);
	}

	@Override
	public void destroy() {}

	@Override
	public void init() {}

	public String getRedirectUrl() {
		return redirectUrl;
	}

	public void setRedirectUrl(String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}

	public String getRoleToCheck() {
		return roleToCheck;
	}

	public void setRoleToCheck(String roleToCheck) {
		this.roleToCheck = roleToCheck;
	}

}
